package com.itcpeng.security.impl;

import com.itcpeng.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;


public class MyUserServiceImpl implements UserDetailsService {

    //认证登陆时 security就会来调用这个方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用dao
        User byUserName = findByUserName(username);
        if (byUserName != null) {
            //密码校验 交给security
            List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();//用户权限的集合
            //权限  , 这里可以是角色名 也可以是权限名
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
            list.add(grantedAuthority);
            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User( byUserName.getUsername(),byUserName.getPassword(), list);
            return user;
        }
        return null;
    }

    public User findByUserName(String username) {
        User user = null;
        if ("admin".equals(username)) {
            user = new User();
            user.setId(5456);
            user.setPassword("$2a$10$Rgf/hCFQkSmC2t9img1udeED3zEW5gABqVfADxWZK7wz3ouJa7iaW");
            user.setUsername("admin");
        }
        return user;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        System.out.println(encoder.encode("1234"));
        System.out.println(encoder.matches("1234","$2a$10$u9vtWLNaynQVbJEmWAvvx.jl2yPWXQaN8JIAQsPGiOv/N1fgX84sa"));

    }
}
